package org.common.utils.rpc.net;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.common.utils.net.netty.core.NettyDecode;
import org.common.utils.net.netty.core.NettyEncode;
import org.common.utils.rpc.net.serialization.RpcSerialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * RPC编码器
 * @author zhouzhibing
 * @date 2025/11/16 17:56
 */
@ChannelHandler.Sharable
public class RpcNettyEnCode extends NettyEncode {

    private static final Logger log = LoggerFactory.getLogger(NettyEncode.class);

    private final RpcSerialization serializable;


    public RpcNettyEnCode(RpcSerialization serializable) {
        this.serializable = serializable;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        try {
            byte[] serialize = serializable.serialize(msg);
            out.writeInt(serialize.length);
            out.writeBytes(serialize);
        } catch (Exception e) {
            log.error("RpcNettyEnCode encode error", e);
        }
    }
}
